package com.lmpop.trade.backupDB;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

import com.lmpop.frame.util.Config;

public class DataMgr
{
  Config cfg = null;
  SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

  private String _username = "";
  private String _password = "";
  private String _database = "";
  private String _host = "";
  private String _port = "";
  private String database_backup_files_path = "";
  private String database_tools_path = "";
  private String _root_path = "";
  private String _driver = "";

  public DataMgr(String username, String password, String database, String host, String port)
  {
    this._username = username;
    this._password = password;
    this._database = database;
    this._host = host;
    this._port = port;
  }

  public DataMgr()
  {
    this.cfg = new Config();
    this.cfg.init("config.properties");
    this._username = this.cfg.getString("username");
    this._password = this.cfg.getString("password");
    this._database = this.cfg.getString("mysqlbase.sid");
    this._host = this.cfg.getString("mysqlbase.host");
    this._port = this.cfg.getString("mysqlbase.port");
    this._root_path = this.cfg.getString("rootpath");
    this.database_backup_files_path = (this._root_path + this.cfg.getString("database_backup_files_path"));
    this.database_tools_path = (this._root_path + this.cfg.getString("database_tools_path"));
    this._driver = this.cfg.getString("driver");
  }

  public ArrayList getTables()
  {
    JDBCExceute jdbc = new JDBCExceute();
    ArrayList list = jdbc.excute("show table");
    return list;
  }

  public boolean backup(String targetName)
  {
    String backFilePath = "";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String backDirString = this.database_backup_files_path + "database/";
    File tableDir = new File(this.database_backup_files_path + "/tables/");
    try
    {
      if (!targetName.equals(this._database)) {
        if (!tableDir.exists()) {
          tableDir.mkdir();
        }
        backFilePath = this.database_backup_files_path + "tables/" + targetName + ".sql";
      }
      else {
        backFilePath = this.database_backup_files_path + "database/" + targetName + "_" + sdf.format(new Date()) + ".sql";
        File backDir = new File(backDirString);
        if (!backDir.exists()) {
          backDir.mkdir();
        }
      }

      File backFile = new File(backFilePath);
      if (backFile.exists()) {
        backFile.delete();
      }
      Runtime runt = Runtime.getRuntime();
      System.out.println("-------------before-backup-------------->");
      Process proc = runt.exec(getBackupShellString(targetName));
      int tag = proc.waitFor();

      return tag == 0;
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }return false;
  }

  public String getBackupShellString(String targetName)
  {
    String backFile = "";
    if (targetName.equals(this._database)) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
      backFile = this.database_backup_files_path + "database/" + targetName + "_" + sdf.format(new Date()) + ".sql";
      targetName = "";
    } else {
      backFile = this.database_backup_files_path + "tables/" + targetName + ".sql";
    }

    String OSType = System.getProperty("os.name");
    String shellStr = "";
    if (OSType.indexOf("Windows") != -1) {
      shellStr = this.database_tools_path + "mysqldumpwin.exe -h " + this._host + " -P" + this._port + "   -u" + this._username + " -p" + this._password + " --result-file=" + backFile + " --default-character-set=gbk " + this._database + " " + targetName;
    }
    else {
      shellStr = this.database_tools_path + "mysqldump -h " + this._host + " -P" + this._port + "   -u" + this._username + " -p" + this._password + " --result-file=" + backFile + " --default-character-set=gbk " + this._database + " " + targetName;
    }

    System.out.println("##############" + shellStr);
    return shellStr;
  }

  public static ArrayList getBakInfo(String filePath)
  {
    String savePath = filePath + "/database/";
    File file = new File(savePath);
    if (!file.exists()) {
      return null;
    }
    if (!file.isDirectory()) {
      return null;
    }
    String[] tempList = file.list();
    Arrays.sort(tempList);
    ArrayList list = new ArrayList();
    for (int i = tempList.length - 1; i >= 0; i--) {
      File temp = new File(savePath + tempList[i]);
      if (temp.isFile()) {
        DataFile t = new DataFile();
        t.setFileName(tempList[i]);
        t.setFileSize(temp.length());
        t.setSavePath(temp.getPath());
        list.add(t);
      }
    }
    return list;
  }

  public boolean restore(String targetName)
  {
    try
    {
      Runtime runt = Runtime.getRuntime();

      String cmdtext = getRestoreShellString(targetName);
      Process proc;
      if (System.getProperty("os.name").indexOf("Windows") != -1) {
        String[] cmd = { "cmd", "/c", cmdtext };
        proc = runt.exec(cmd);
      } else {
        String[] cmd = { "sh", "-c", cmdtext };
        proc = runt.exec(cmd);
      }
      System.out.println(cmdtext);

      int tag = proc.waitFor();

      return tag == 0;
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return false;
  }

  public String getRestoreShellString(String targetName)
  {
    String backFile = "";
    if (targetName.indexOf(this._database) == -1)
      backFile = this.database_backup_files_path + "tables/" + targetName + ".sql";
    else {
      backFile = this.database_backup_files_path + "database/" + targetName;
    }

    String OSType = System.getProperty("os.name");
    String shellStr = "";
    if (OSType.indexOf("Windows") != -1) {
      shellStr = this.database_tools_path + "mysqlwin.exe -h " + this._host + " -P" + this._port + "   -u" + this._username + " -p" + this._password + " --default-character-set=gbk " + this._database + " < " + backFile;
    }
    else {
      shellStr = this.database_tools_path + "mysql -h " + this._host + " -P" + this._port + "   -u" + this._username + " -p" + this._password + "   --default-character-set=gbk " + this._database + " < " + backFile;
    }

    return shellStr;
  }

  public int createDB() throws Exception {
    Class.forName(this._driver);
    String myurl = "jdbc:mysql://" + this._host + ":" + this._port + "/" + this._database;
    String url = "jdbc:mysql://" + this._host + ":" + this._port + "/mysql";
    Connection mycon = null;
    try {
      mycon = DriverManager.getConnection(myurl, this._username, this._password);
    } catch (SQLException e) {
    }
    if (mycon != null) {
      return 1;
    }
    Connection con = null;
    try {
      con = DriverManager.getConnection(url, this._username, this._password);
    } catch (SQLException e) {
    }
    if (con == null) {
      return 0;
    }
    Statement st = con.createStatement();
    st.execute("create   database   `" + this._database + "`");
    return 1;
  }

  public void delBakFile(String fileName)
  {
    String filepath = this.database_backup_files_path + "database/" + fileName;
    File delFile = new File(filepath);
    if (delFile.exists())
      delFile.delete();
  }

  public String get_database()
  {
    return this._database;
  }
  public void set_database(String _database) {
    this._database = _database;
  }
  public String get_password() {
    return this._password;
  }
  public void set_password(String _password) {
    this._password = _password;
  }
  public String get_username() {
    return this._username;
  }
  public void set_username(String _username) {
    this._username = _username;
  }
}